package cn.open.feishu.alert.support.Handler;

import cn.open.feishu.alert.common.annotation.AlertHandler;
import cn.open.feishu.alert.common.enums.AlertModeEnum;
import cn.open.feishu.alert.common.enums.AlertTypeEnum;
import cn.open.feishu.alert.common.model.CardAlertRequest;
import cn.open.feishu.alert.common.model.PrivateCardAlertRequest;
import cn.open.feishu.alert.common.model.PrivateCardAlertResponse;
import cn.open.feishu.alert.common.utils.HttpUtil;
import cn.open.feishu.alert.config.ButtonProperties;
import cn.open.feishu.alert.config.FeiShuProperties;
import cn.open.feishu.alert.support.FeishuAlertClient;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import static cn.open.feishu.alert.common.FeishuConstant.SUCCESS_CODE;

/**
 * @Description 飞书消息下发客户端
 * @Author fandy.lin
 * @Date 2021/11/26 2:10 下午
 **/
@Slf4j
@AlertHandler(AlertModeEnum.SEND_CHARGE_PERSON_USE_APP_ROBOT)
public class PrivateFeishuAlertHandler extends BaseFeishuAlertHandler implements FeishuAlertHandler {
    public PrivateFeishuAlertHandler(Environment env, FeiShuProperties feiShuProperties, ButtonProperties buttonProperties, FeishuAlertClient feishuAlertClient) {
        super(env, feiShuProperties, buttonProperties, feishuAlertClient);
    }

    @Override
    public void send(String robotName, String alertText, AlertTypeEnum alertType) {
        String realSendUrl = feiShuProperties.getAppSendUrl();
        CardAlertRequest alertReq = null;
        try {
            //构建卡片请求
            alertReq = buildCardRequest(alertText, alertType, true);
            //获取token缓存
            Map<String, String> tokenMap = feishuAlertClient.getTokenMap();
            if(Objects.isNull(alertReq) && Objects.isNull(tokenMap)){
                log.warn("feishu alert:send private alert fail,alertReq={},tokenMap={}",alertReq,tokenMap);
                return;
            }
            //发送告警消息
            PrivateCardAlertResponse alertResp = HttpUtil.execute(realSendUrl, tokenMap, alertReq, PrivateCardAlertResponse.class);
            if (SUCCESS_CODE != alertResp.getCode()) {
                log.warn("feishu alert:send private alert fail,ret code={},msg={}", alertResp.getCode(), alertResp.getCode());
            }
        } catch (IOException e) {
            log.error("feishu alert:send private alert error,send url={},req={}", realSendUrl, JSON.toJSONString(alertReq), e);
        }
    }

    @Override
    protected CardAlertRequest buildCardRequest(String alertText, AlertTypeEnum alertType, Boolean isAt) {
        if(!feishuAlertClient.existUser()){
            return  null;
        }
        CardAlertRequest alertRequest = super.buildCardRequest(alertText, alertType, isAt);
        return new PrivateCardAlertRequest(alertRequest.getMsg_type(),alertRequest.getCard(),feishuAlertClient.getUserIds());
    }
}
